//
//  SRMainVc.m
//
//
//  Created by   on 2022/5/5.
//

#import <Toast.h>
#import <DateTools/DateTools.h>
#import "CAMainVc.h"
#import "CARingSDK.h"
#import "CABLeService.h"
#import "CAConnectVc.h"
#import "CAOutsideConnectVc.h"
#import "SRfileTableViewController.h"
#import "CADeviceInfo.h"
#import "UILabel+styles.h"
#import "CASettingVc.h"
#import "SetUserInfoVC.h"
//#import "SleepStagingV2.h"
#import <QMUIKit/QMUIKit.h>
#import "ConfigModel.h"
#import "DynamicTextView.h"
#import "CADeviceInfo+description.h"
#import "UIButton+demoStyle.h"
#import "FunctionButton.h"
#import "Colors.h"
#import "UUidVc.h"
#import "CAActivityObjsHead.h"
#import "CAActivityObjsCategoHead.h"
#import "WorkoutVc.h"
#import "SleepVc.h"
#import "SepLineView.h"
#import "MeasurtimeparamVc.h"
#import "CAEcgMeasureVc.h"
#import "OTAHelper.h"
#import "CAOTAVc.h"


NSString * const CP_aabo = @"aabo";

@interface CAMainVc ()<CABleDataProtocal, CABleScanProtocal>

//@property(strong, nonatomic)FunctionButton *meaFingerRadiusBtn; // 测量手指

@property(strong, nonatomic)FunctionButton *bindQuseryBtn, *bindSetBtn, *oemAuthSwitchBtn, *syncTimeBtn, *qryusrInfBtn,*setUsrInfoBtn ,*shutBTn ,*rebootBtn, *factoryRstBtn , *batteryBtn, *qryRealAvtivityBtn;

@property(strong, nonatomic)FunctionButton *qryhistory1Btn,*qryHis2CntBtn, *qryHis2DataBtn, *cleanHisOneBtn, *cleanHisTwoBtn, *hrSpoRealMeaBtn;

@property(strong, nonatomic)FunctionButton *workoutFuncBtn, *calcSleepBtn, *measureTimeSetBtn, *otaBtn, *ecgBtn, *deviceInfoBtn;

@property(strong, nonatomic)FunctionButton * cleanTxtBtn;

//@property(strong, nonatomic)UITableView *tableView;
//@property(strong, nonatomic)NSArray<NSNumber *> *dataArray;

@property(strong, nonatomic)NSNumber *hrValue, *HRVValue, *oxygenValue, *stpes, *temperature, *battery, *isCHarge, *voltage;


@property(strong, nonatomic)UILabel *topLable;

@property(strong, nonatomic)QMUIButton *bleBtn, *settingBtn;

@property(strong, nonatomic)UIScrollView *btnScrollView;
@property(strong, nonatomic)DynamicTextView *textView;

@property(assign, nonatomic)NSInteger his_1_countIdx, his_1_allCount;
@property(strong, nonatomic)CADeviceInfo *deviceInfo;
//@property(strong, nonatomic)SleepStagingV2 *sleepStage;
@end

@implementation CAMainVc

-(instancetype)init
{
    if (self = [super init])
    {
        [[CARingSDK instance] registWithCompanyArray:@[ CP_aabo]];  // initlize sdk

        [CARingSDK.instance registECGKey:@"2901f7613ac7403e9c5fbc0248b6d94f" Secret:@"ad58bea443d04368beb847510a37a99d"];
        
        // 新广播包解析 的 cid标识
        [[CARingSDK instance] setBroadCastAnalyCids: @[
            @[@(0XAD), @(0X0D) ],  // sr28
        ]
        ];
        
        [CARingSDK instance].bleDataDelegate = self;
        [CARingSDK instance].blescanDelegate = self;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
    self.ousideBleManager.cAscanDelegate = self;
    
    
    // 首次今入的连接
    if (CARingSDK.instance.currentDevice == nil
        && self.caService != nil)
    {
        [self.ousideBleManager connectCaPeripheral:self.caService];
        
//        [CARingSDK.instance connectDevice:self.caService];
    }
    
 
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.ousideBleManager.cAscanDelegate = self;

}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [CARingSDK instance].bleDataDelegate = self;
    [CARingSDK instance].blescanDelegate = self;
    
    if ([[CARingSDK instance] currentDevice].isConnected != YES) { // not connected
        self.bleBtn.selected = NO;
        self.topLable.text = nil;

    } else {
        
        self.bleBtn.selected = YES;

        // get battery
        
//        [[LTSRingSDK instance] functionGetDeviceInfo];
        
        if ([[CARingSDK instance] currentDevice].advDataLocalName) {
            self.topLable.text = [NSString stringWithFormat:@"%@\r\n%@", [[CARingSDK instance] currentDevice].advDataLocalName, [[CARingSDK instance] currentDevice].macAddress];
        }
    }

}

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    self.btnScrollView.contentSize = CGSizeMake(self.btnScrollView.bounds.size.width, CGRectGetMaxY(self.btnConten.frame));
}


-(void)initUI {
    
    [self customCenterTitle:[ConfigModel appName]];
    
    UIBarButtonItem *itemBle = [[UIBarButtonItem alloc] initWithCustomView:self.bleBtn];
    UIBarButtonItem *itemSeting = [[UIBarButtonItem alloc] initWithCustomView:self.settingBtn];

    self.navigationItem.rightBarButtonItems = @[itemSeting,itemBle, ];
    
//    [self.view addSubview:self.tableView];
    [self.view addSubview:self.topLable];
    [self.view addSubview:self.textView];
    
    [self.view addSubview:self.btnScrollView];
    
    [self.view addSubview:self.cleanTxtBtn];
    
    [self.topLable mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.topLable.superview).offset(8);
        make.trailing.equalTo(self.topLable.superview);
        make.top.equalTo(self.topLable.superview).offset(10);
        make.height.equalTo(@40);
    }];
    
    UILabel *sdkVerLbl = [UILabel new];
    [self.view addSubview:sdkVerLbl];
    sdkVerLbl.textAlignment = NSTextAlignmentRight;
    sdkVerLbl.text = [NSString stringWithFormat:@"SDK Version:%@", [CARingSDK.instance sdkVersion]];
    [sdkVerLbl mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(sdkVerLbl.superview.mas_trailing).inset(15);
        make.top.equalTo(self.topLable);
    }];
    
    
    
    [self.textView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.topLable.mas_bottom);
        make.leading.equalTo(self.view).offset(8);
        make.trailing.equalTo(self.view).inset(8);

        make.height.equalTo(self.view.mas_height).multipliedBy(1/3.0);
    }];
    
    [self.cleanTxtBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.textView.mas_bottom).offset(15);
        make.leading.equalTo(self.textView);
        make.height.equalTo(@35);
        make.width.equalTo(@180);
    }];
    
   
    SepLineView *sep = [[SepLineView alloc]init];
    [self.view addSubview:sep];
    [sep mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.view);
        make.top.equalTo(self.cleanTxtBtn.mas_bottom).offset(5);
        make.height.equalTo(@1);
    }];
    
    
    [self.btnScrollView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.view);
        make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom).inset(15);
        make.top.equalTo(self.cleanTxtBtn.mas_bottom).offset(15);
//        make.height.equalTo(@200);
    }];
//    btnConten.backgroundColor = UIColor.greenColor;
    
    [self layoutBtnContent];
    
}

/// down image an ota
-(void)downlodOTA
{
    if (!self.deviceInfo) { // need deviceinfo
        NSString *str = @"Click button \"Device's Info\".";
        [self showAlertWarningWithTitle:@"Tips" Msg:[NSString stringWithFormat:@"%@%@", _L2(L_GET_DEVINFO_FIRST), str] btnOk:_L2(L_Sure) OkBLk:nil CancelBtn:nil CancelBlk:nil Compelete:nil];
        return;
    }
    
    //
    NSString *catFordownload = [self.deviceInfo chooseOTAugument];
    [[LTPHud Instance] showHud];
    WEAK_SELF
    [[OTAHelper Instance] otaQueryUpgrade:OTA_HOST Cat:catFordownload CBK:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error, NSDictionary * _Nullable resultDict) {
        STRONG_SELF
        /*
         {'ver': '0.1.8',  // version number
          'desc': 'V0.1.8', // Version number description
          'sign': 'bb794b6dc3a7344de798e801e9947597',
         'uri': 'http://linktop.ltd:9037/ota/7d4edf7766', //Firmware download address
         'size': 37056 // Firmware size unit: bytes
         }
         */
        DebugNSLog(@"ota 请求statecode = %ld, %@", (long)((NSHTTPURLResponse *)response).statusCode , resultDict);
        BOOL needUpdate = [strongSelf.deviceInfo checkNeedUpdate:resultDict[@"ver"]];
        if (needUpdate) {
            if (resultDict) {
                [OTAHelper Instance].imgObj = [[OTAImgObj alloc]initWithDict:resultDict];
                [OTAHelper Instance].imgObj.downLoadCBK = ^(NSURL * _Nonnull imgFileUrl) {
                    [[LTPHud Instance] hideHud];
                    if (imgFileUrl) {
                        [strongSelf tipsToUpdrade:imgFileUrl];
                    } else {
                        // 下载失败
                        [strongSelf showAlertWarningWithTitle:@"Tips" Msg:@"Firmware download failed, please try again." btnCancel:@"Ok" Compelete:nil];
                    }
                    
                };
                [[OTAHelper Instance].imgObj caDownload];
                
            } else {
                [[LTPHud Instance] hideHud];
            }
        } else {
            [[LTPHud Instance] hideHud];

            // 无需升级
            [strongSelf showAlertWarningWithTitle:@"Tips" Msg:@"Already the latest firmware!" btnCancel:@"Ok" Compelete:nil];
        }
        
      
        
    }];
    
    
}

-(void)tipsToUpdrade:(NSURL * _Nonnull )imgFileUrl {
    WEAK_SELF
    [self showAlertWarningWithTitle:@"Tips" Msg:@"There is a new device software that can be updated, do you want to update it now?" btnOk:@"Update now" OkBLk:^{
        STRONG_SELF
        CAOTAVc *otaVc = [[CAOTAVc alloc]init];
        otaVc.ousideBleDiscovery = strongSelf.ousideBleManager;
        otaVc.updateImageFileUrl = imgFileUrl;
        otaVc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:otaVc animated:YES];
        
    } CancelBtn:@"Cancel" CancelBlk:nil Compelete:nil];
    
}

#pragma mark -- Buttons
-(void)layoutBtnContent
{
    UIView *content = [UIView new];
    [self.btnScrollView addSubview:content];
    self.btnConten = content;
    
    [content mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(content.superview).offset(3);
        make.trailing.equalTo(content.superview).inset(3);

        make.top.equalTo(content.superview).offset(0);
        make.bottom.equalTo(content.superview.mas_bottom).inset(5);
        make.centerX.equalTo(content.superview.mas_centerX);
    }];

    NSArray<UIButton *> *btnsArray = @[
        self.bindQuseryBtn, self.bindSetBtn,
        self.hrSpoRealMeaBtn,self.deviceInfoBtn,
        self.oemAuthSwitchBtn, self.syncTimeBtn,
        self.qryusrInfBtn,self.setUsrInfoBtn,
        self.batteryBtn, self.shutBTn ,
        self.rebootBtn, self.factoryRstBtn,
        self.qryRealAvtivityBtn, self.qryhistory1Btn,
        self.qryHis2CntBtn, self.qryHis2DataBtn,
        self.cleanHisOneBtn, self.cleanHisTwoBtn,
        //                                       self.settingBtn,
        self.otaBtn, self.workoutFuncBtn,
        self.calcSleepBtn, self.measureTimeSetBtn,
        self.ecgBtn,
    ];
    
    [btnsArray enumerateObjectsUsingBlock:^(UIButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [content addSubview:obj];
    }];
  
    NSUInteger hor = 2;
    
    for (int i = 0; i < btnsArray.count; i++) {
        UIButton *btn = btnsArray[i];
        
        [btn mas_remakeConstraints:^(MASConstraintMaker *make) {
            if (i == 0) {
                make.leading.top.equalTo(btn.superview);
            }
            
            if (i !=0 && i % hor == 0) {
                make.leading.equalTo(btnsArray[i-2].mas_leading);
                make.top.equalTo(btnsArray[i-2].mas_bottom).offset(5);
                make.trailing.equalTo(btnsArray[i-2].mas_trailing);
            }
            
            if ( i % hor > 0) {
                make.leading.equalTo(btnsArray[i-1].mas_trailing).offset(5);
                make.top.equalTo(btnsArray[i-1].mas_top);
                make.trailing.equalTo(btn.superview.mas_trailing);
                make.width.equalTo(btnsArray[i-1].mas_width);
            }
            
            
            if (i == btnsArray.count - 1) {
                make.bottom.equalTo(content.mas_bottom);
            }
            
            make.height.equalTo(@40);
            
        }];
        
    }
    
    [self.btnScrollView setNeedsLayout];
    [self.view layoutIfNeeded];
   
}


#pragma mark --lazy

//-(FunctionButton *)meaFingerRadiusBtn
//{
//    if (!_meaFingerRadiusBtn) {
//        _meaFingerRadiusBtn = [FunctionButton functionButton:@"计算尺寸"];
//        WEAK_SELF
//        [_meaFingerRadiusBtn addTapBlk:^(FunctionButton * _Nonnull btn) {
//            STRONG_SELF
////            [LTSRingSDK.instance functionGetDeviceSN];
//            FinderDetecVc *vc = [[FinderDetecVc alloc]init];
//            vc.hidesBottomBarWhenPushed = YES;
//            [strongSelf.navigationController pushViewController:vc animated:YES];
//        }];
//    }
//    return _meaFingerRadiusBtn;
//}


-(FunctionButton *)bindQuseryBtn
{
    if (!_bindQuseryBtn) {
        _bindQuseryBtn = [FunctionButton functionButton:_L2(L_get_bind_sta)];
        WEAK_SELF
        [_bindQuseryBtn addTapBlk:^(FunctionButton * _Nonnull btn) {
            STRONG_SELF
            [CARingSDK.instance functionGetDeviceSN];
        }];
    }
    return _bindQuseryBtn;
}

-(FunctionButton *)qryusrInfBtn
{
    if (!_qryusrInfBtn) {
        _qryusrInfBtn = [FunctionButton functionButton:_L2(L_sur_info_in_ring)];
        WEAK_SELF
        [_qryusrInfBtn addTapBlk:^(FunctionButton * _Nonnull btn) {
            STRONG_SELF
            [CARingSDK.instance functionGetUsrInfoFromDev];
        }];
    }
    return _qryusrInfBtn;
}

-(FunctionButton *)syncTimeBtn
{
    if (!_syncTimeBtn) {
        _syncTimeBtn = [FunctionButton functionButton:_L2(L_set_time_to_ring)];
        WEAK_SELF
        [_syncTimeBtn addTapBlk:^(FunctionButton * _Nonnull btn) {
            STRONG_SELF
            if (!CARingSDK.instance.currentDevice.isConnected) {
                return;
            }
            NSDate *date = [NSDate date];
            [CARingSDK.instance functionSyncTime:date];
            
            [strongSelf.textView addNewText:[NSString stringWithFormat:@"Sync to:%@", [date formattedDateWithFormat:_L2(L_DATE_FMT)]] ];
        }];
    }
    return _syncTimeBtn;
}


-(FunctionButton *)shutBTn
{
    if (!_shutBTn) {
        _shutBTn = [FunctionButton functionButton:_L2(L_shutdown)];
        WEAK_SELF
        [_shutBTn addTapBlk:^(FunctionButton * _Nonnull btn) {
            STRONG_SELF
            [CARingSDK.instance functionShutDownDevice];

        }];
    }
    return _shutBTn;
}
-(FunctionButton *)rebootBtn
{
    if (!_rebootBtn) {
        _rebootBtn = [FunctionButton functionButton:_L2(L_Reboot)];
        WEAK_SELF
        [_rebootBtn addTapBlk:^(FunctionButton * _Nonnull btn) {
            STRONG_SELF
            [CARingSDK.instance functionRebootDevice];

        }];
    }
    return _rebootBtn;
}
-(FunctionButton *)factoryRstBtn
{
    if (!_factoryRstBtn) {
        _factoryRstBtn = [FunctionButton functionButton:@"Reset to factory"];
        WEAK_SELF
        [_factoryRstBtn addTapBlk:^(FunctionButton * _Nonnull btn) {
            STRONG_SELF
            if (!CARingSDK.instance.currentDevice.isConnected) {
                return;
            }
            [strongSelf showAlertWarningWithTitle:@"Tips" Msg:@"Click OK to restore to factory settings. All data will be cleared. The ring needs to be placed on the charging stand for it to be scanned." btnOk:_L2(L_OK) OkBLk:^{
                STRONG_SELF
                [CARingSDK.instance functionDeviceReset];

            } CancelBtn:_L2(L_CANCEL) CancelBlk:^{
                STRONG_SELF
                
            } Compelete:nil];
        }];
    }
    return _factoryRstBtn;
}


-(FunctionButton *)setUsrInfoBtn
{
    if (!_setUsrInfoBtn) {
        _setUsrInfoBtn = [FunctionButton functionButton:_L2(L_set_usr_inf_to_ring)];
        WEAK_SELF
        [_setUsrInfoBtn addTapBlk:^(FunctionButton * _Nonnull btn) {
            STRONG_SELF
//            [LTSRingSDK.instance functionGetUsrInfoFromDev];
            
            SetUserInfoVC *setUserInfoVc = [[SetUserInfoVC alloc]init];
            [strongSelf presentViewController:setUserInfoVc animated:YES completion:nil];
            
        }];
    }
    return _setUsrInfoBtn;
}

-(FunctionButton *)qryRealAvtivityBtn
{
    if (!_qryRealAvtivityBtn) {
        _qryRealAvtivityBtn = [FunctionButton functionButton:_L2(L_get_real_activity)];
        WEAK_SELF
        [_qryRealAvtivityBtn addTapBlk:^(FunctionButton * _Nonnull btn) {
            STRONG_SELF
            [CARingSDK.instance functionGetLastActivity];
            
        }];
    }
    return _qryRealAvtivityBtn;
}

-(FunctionButton *)qryHis2CntBtn {
    if (!_qryHis2CntBtn) {
        _qryHis2CntBtn = [FunctionButton functionButton:_L2(L_get_his_2_cnt)];
        WEAK_SELF
        [_qryHis2CntBtn addTapBlk:^(FunctionButton * _Nonnull btn) {
            STRONG_SELF
            [CARingSDK.instance functionGetHistoryCntOfActvtyDtctAndSwimAndSleepHisty];
            
        }];
    }
    return _qryHis2CntBtn;
}

-(FunctionButton *)qryHis2DataBtn
{
    if (!_qryHis2DataBtn) {
        _qryHis2DataBtn = [FunctionButton functionButton:_L2(L_get_his_2_data)];
        WEAK_SELF
        [_qryHis2DataBtn addTapBlk:^(FunctionButton * _Nonnull btn) {
            STRONG_SELF
            UIAlertController * alertVc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
            
            UIAlertAction *actionBind = [UIAlertAction actionWithTitle:@"All" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                STRONG_SELF
                [[CARingSDK instance] functionGetHstryDataOfActvtyDetectAndSwimAndSlep];// get all history2
                
            }];

            [alertVc addAction:actionBind];
            
            UIAlertAction * actionUnbind = [UIAlertAction actionWithTitle:@"UUid Range" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                STRONG_SELF
                UUidVc *uuidVc = [[UUidVc alloc] init];
                uuidVc.cbK = ^(NSUInteger uuidMax) {
                    STRONG_SELF
                    [[CARingSDK instance] functionGetHstryDataOfActvtyDetectAndSwimAndSlepMaxUUid:(uint32_t)uuidMax];

                };
                [strongSelf presentViewController:uuidVc animated:YES completion:nil];

            }];;
           
            [alertVc addAction:actionUnbind];
          
                
            UIAlertAction * actionCancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
            [alertVc addAction:actionCancel];

            [strongSelf presentViewController:alertVc animated:YES completion:nil];
            
            
            
        }];
    }
    return _qryHis2DataBtn;
}

-(FunctionButton *)cleanHisOneBtn
{
    if (!_cleanHisOneBtn) {
        _cleanHisOneBtn = [FunctionButton functionButton:_L2(L_clean_his_1)];
        WEAK_SELF
        [_cleanHisOneBtn addTapBlk:^(FunctionButton * _Nonnull btn) {
            STRONG_SELF
            [CARingSDK.instance functionClearDeviceHistoryCache];
        }];
    }
    return _cleanHisOneBtn;
}
-(FunctionButton *)cleanHisTwoBtn
{
    if (!_cleanHisTwoBtn) {
        _cleanHisTwoBtn = [FunctionButton functionButton:_L2(L_clean_his_2)];
        WEAK_SELF
        [_cleanHisTwoBtn addTapBlk:^(FunctionButton * _Nonnull btn) {
            STRONG_SELF
            [CARingSDK.instance functionCleanActivityHistory];
        }];
    }
    return _cleanHisTwoBtn;
}

-(FunctionButton *)workoutFuncBtn
{
    if (!_workoutFuncBtn) {
        _workoutFuncBtn = [FunctionButton functionButton:_L2(L_TX_WORKOUT)];
        WEAK_SELF
        [_workoutFuncBtn addTapBlk:^(FunctionButton * _Nonnull btn) {
            STRONG_SELF
            if (!CARingSDK.instance.currentDevice.isConnected) {
                [LTPHud.Instance showText:_L2(L_TIP_BLE_NOT_CONNECT)];
                return;
            }
            WorkoutVc *wkVc = [[WorkoutVc alloc]init];
            wkVc.hidesBottomBarWhenPushed = YES;
            [strongSelf.navigationController pushViewController:wkVc animated:YES];
//            [LTSRingSDK.instance functionCleanActivityHistory];
            
        }];
    }
    return _workoutFuncBtn;
}

-(FunctionButton *)calcSleepBtn
{
    if (!_calcSleepBtn) {
        _calcSleepBtn = [FunctionButton functionButton:_L2(L_calc_sleep)];
        WEAK_SELF
        [_calcSleepBtn addTapBlk:^(FunctionButton * _Nonnull btn) {
            STRONG_SELF
            if (!CARingSDK.instance.currentDevice.isConnected) {
                [LTPHud.Instance showText:_L2(L_TIP_BLE_NOT_CONNECT)];
                return;
            }
            SleepVc *sleepVc = [[SleepVc alloc]init];
            sleepVc.hidesBottomBarWhenPushed = YES;
            [strongSelf.navigationController pushViewController:sleepVc animated:YES];
//            [LTSRingSDK.instance functionCleanActivityHistory];
            
        }];
    }
    return _calcSleepBtn;
}


-(FunctionButton *)batteryBtn
{
    if (!_batteryBtn) {
        _batteryBtn = [FunctionButton functionButton:_L2(L_pwer_percetn)];
        WEAK_SELF
        [_batteryBtn addTapBlk:^(FunctionButton * _Nonnull btn) {
            STRONG_SELF
            [CARingSDK.instance functionGetDeviceBattery];
        }];
    }
    return _batteryBtn;
}

-(FunctionButton *)bindSetBtn
{
    if (!_bindSetBtn) {
        _bindSetBtn = [FunctionButton functionButton:_L2(L_set_bind_sta)];
        WEAK_SELF
        [_bindSetBtn addTapBlk:^(FunctionButton * _Nonnull btn) {
            STRONG_SELF
            UIAlertController * alertVc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
            
            UIAlertAction *actionBind = [UIAlertAction actionWithTitle:@"Set to Binded" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                STRONG_SELF
                [[CARingSDK instance] functionSetBindeDevice:YES];
                
            }];

            [alertVc addAction:actionBind];
            
            UIAlertAction * actionUnbind = [UIAlertAction actionWithTitle:@"Set to Unbinded" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                STRONG_SELF
                [[CARingSDK instance] functionSetBindeDevice:NO];

            }];;
           
            [alertVc addAction:actionUnbind];
          
                
            UIAlertAction * actionCancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
            [alertVc addAction:actionCancel];

            [strongSelf presentViewController:alertVc animated:YES completion:nil];
        }];
    }
    return _bindSetBtn;
}

-(FunctionButton *)oemAuthSwitchBtn
{
    if (!_oemAuthSwitchBtn) {
        _oemAuthSwitchBtn = [FunctionButton functionButton:_L2(L_oem_auth_switch)];
        WEAK_SELF
        [_oemAuthSwitchBtn addTapBlk:^(FunctionButton * _Nonnull btn) {
            
            if (!CARingSDK.instance.currentDevice.isConnected) {
                [LTPHud.Instance showText:_L2(L_TIP_BLE_NOT_CONNECT) Lasting:2];
                return;
            }
            
            STRONG_SELF
            UIAlertController * alertVc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
            
            UIAlertAction *actionOn = [UIAlertAction actionWithTitle:@"Turn On" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                STRONG_SELF
                
                [[CARingSDK instance] functionSetOEMAuthSwitch:YES];
                
            }];

            [alertVc addAction:actionOn];
            
            UIAlertAction * actionOff = [UIAlertAction actionWithTitle:@"Turn Off" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                STRONG_SELF
                
                [[CARingSDK instance] functionSetOEMAuthSwitch:NO];

            }];;
           
            [alertVc addAction:actionOff];
          
                
            UIAlertAction * actionCancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
            [alertVc addAction:actionCancel];

            [strongSelf presentViewController:alertVc animated:YES completion:nil];
        }];
    }
    return _oemAuthSwitchBtn;
}


-(FunctionButton *)otaBtn
{
    if (!_otaBtn) {
        _otaBtn = [FunctionButton functionButton:@"OTA"];
        WEAK_SELF
        [_otaBtn addTapBlk:^(FunctionButton * _Nonnull btn) {
            STRONG_SELF
            
            UIAlertController * alertVc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
            
            UIAlertAction *actionLocal = [UIAlertAction actionWithTitle:@"Image From Local" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                STRONG_SELF
                if (CARingSDK.instance.currentDevice.isConnected) {
                    SRfileTableViewController *otaVC = [[SRfileTableViewController alloc]init];
                    otaVC.hidesBottomBarWhenPushed = YES;
                    [strongSelf.navigationController pushViewController:otaVC animated:YES];
                } else {
                    [LTPHud.Instance showText:_L2(L_TIP_BLE_NOT_CONNECT) Lasting:2];
                }
            }];

            [alertVc addAction:actionLocal];
            
            UIAlertAction * actionDownload = [UIAlertAction actionWithTitle:@"Download Image to OTA" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                STRONG_SELF
                [strongSelf downlodOTA];
                
            }];;
           
            [alertVc addAction:actionDownload];
        
            UIAlertAction * actionCancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
            [alertVc addAction:actionCancel];

            [strongSelf presentViewController:alertVc animated:YES completion:nil];
            
        }];
    }
        
    return _otaBtn;
}

-(FunctionButton *)ecgBtn
{
    if (!_ecgBtn) {
        _ecgBtn = [FunctionButton functionButton:@"ECG"];
        WEAK_SELF
        [_ecgBtn addTapBlk:^(FunctionButton * _Nonnull btn) {
            STRONG_SELF
            if (!strongSelf.deviceInfo) {
                NSString *str = @"Click button \"Device's Info\".";
                [strongSelf showAlertWarningWithTitle:@"Tips" Msg:[NSString stringWithFormat:@"%@%@", _L2(L_GET_DEVINFO_FIRST), str] btnOk:_L2(L_Sure) OkBLk:nil CancelBtn:nil CancelBlk:nil Compelete:nil];
                return;
            }
            
            if (CARingSDK.instance.currentDevice.isConnected) {
                CAEcgMeasureVc *ecgVc = [[CAEcgMeasureVc alloc]init];
                ecgVc.deviceInfo = strongSelf.deviceInfo;
                ecgVc.hidesBottomBarWhenPushed = YES;
                [strongSelf.navigationController pushViewController:ecgVc animated:YES];
                
            } else {
                [LTPHud.Instance showText:_L2(L_TIP_BLE_NOT_CONNECT) Lasting:2];
            }
        }];

    }
        
    return _ecgBtn;
}

-(FunctionButton *)deviceInfoBtn
{
    if (!_deviceInfoBtn) {
        _deviceInfoBtn = [FunctionButton functionButton:@"Device's Info"];
        WEAK_SELF
        [_deviceInfoBtn addTapBlk:^(FunctionButton * _Nonnull btn) {
            STRONG_SELF
            if (CARingSDK.instance.currentDevice.isConnected) {
                [CARingSDK.instance functionGetDeviceInfo];
            } else {
                [LTPHud.Instance showText:_L2(L_TIP_BLE_NOT_CONNECT) Lasting:2];
            }
        }];

    }
    return _deviceInfoBtn;
}

// hisToryBtn
-(FunctionButton *)qryhistory1Btn
{
    if (!_qryhistory1Btn) {
        _qryhistory1Btn = [FunctionButton functionButton:_L2(L_get_his_1_data)];
        WEAK_SELF
        [_qryhistory1Btn addTapBlk:^(FunctionButton * _Nonnull btn) {
            STRONG_SELF
            if (CARingSDK.instance.currentDevice.isConnected) {
                
//                strongSelf.hisCacheArray = [NSMutableArray new];
                
                [CARingSDK.instance functionGetHistoryData];
            } else {
                [LTPHud.Instance showText:_L2(L_TIP_BLE_NOT_CONNECT) Lasting:2];
            }
        }];

    }
    
    return _qryhistory1Btn;
}

-(FunctionButton *)hrSpoRealMeaBtn
{
    if (!_hrSpoRealMeaBtn) {
        _hrSpoRealMeaBtn = [FunctionButton functionButton:@"Realtime Measure"];
        [_hrSpoRealMeaBtn setTitle:@"Turn off Measure" forState:UIControlStateSelected];
        WEAK_SELF
        [_hrSpoRealMeaBtn addTapBlk:^(FunctionButton * _Nonnull btn) {
            STRONG_SELF
            if (!CARingSDK.instance.currentDevice.isConnected) {
                [LTPHud.Instance showText:_L2(L_TIP_BLE_NOT_CONNECT) Lasting:2];
                return;
            }
            if (btn.isSelected) {
                // turn off
                [[CARingSDK instance] functionOxygenAndHrvBoth:YES IsOpen:NO];
                strongSelf.hrSpoRealMeaBtn.selected = NO;
                return;
            }
            
            if (!btn.isSelected) {
                
                UIAlertController * alertVc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
                
                UIAlertAction *actionBind = [UIAlertAction actionWithTitle:@"Heart Rate" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    STRONG_SELF
                    [[CARingSDK instance] functionOxygenAndHrvBoth:NO IsOpen:YES];
                    strongSelf.hrSpoRealMeaBtn.selected = YES;

                }];

                [alertVc addAction:actionBind];
                
                UIAlertAction * actionUnbind = [UIAlertAction actionWithTitle:@"Hr+Spo2" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    STRONG_SELF
                    [[CARingSDK instance] functionOxygenAndHrvBoth:YES IsOpen:YES];
                    strongSelf.hrSpoRealMeaBtn.selected = YES;

                }];;
               
                [alertVc addAction:actionUnbind];
              
                    
                UIAlertAction * actionCancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
                [alertVc addAction:actionCancel];

                [strongSelf presentViewController:alertVc animated:YES completion:nil];
                
                return;
            }
           
        }];

    }
    
    return _hrSpoRealMeaBtn;
}


-(FunctionButton *)cleanTxtBtn
{
    if (!_cleanTxtBtn) {
        _cleanTxtBtn = [FunctionButton functionButton:@"Clean text"];
        WEAK_SELF
        [_cleanTxtBtn addTapBlk:^(FunctionButton * _Nonnull btn) {
            STRONG_SELF
            [strongSelf.textView clearAllText];
        }];
    }
    return _cleanTxtBtn;
}

// MeasurtimeparamVc
-(FunctionButton *)measureTimeSetBtn
{
    if (!_measureTimeSetBtn) {
        _measureTimeSetBtn = [FunctionButton functionButton:_L2(L_MEA_TIME_SET)];
        WEAK_SELF
        [_measureTimeSetBtn addTapBlk:^(FunctionButton * _Nonnull btn) {
            STRONG_SELF
            if (!CARingSDK.instance.currentDevice.isConnected) {
                [LTPHud.Instance showText:_L2(L_TIP_BLE_NOT_CONNECT)];
                return;
            }
            MeasurtimeparamVc *vc = [[MeasurtimeparamVc alloc] init];
            vc.hidesBottomBarWhenPushed = YES;
            [strongSelf.navigationController pushViewController:vc animated:YES];
        }];
    }
    return _measureTimeSetBtn;
}
#pragma mark --SRBleDataProtocal Methods
- (void)caBlePowerStateChange:(CBManagerState)state {
    BOOL isOn;
    switch (state) {
        case CBManagerStateUnsupported:// 不支持蓝牙
        {
            //不支持
            DebugNSLog(@"StateChange = CBManagerStateUnsupported");
        }
            break;
        case CBManagerStatePoweredOff:// 未启动
        {
            DebugNSLog(@"StateChange = CBManagerStatePoweredOff");

           
        }
            break;
        case CBManagerStateUnauthorized: // 未授权
        {
            /* Tell user the app is not allowed. */
            DebugNSLog(@"StateChange = CBManagerStateUnauthorized");

        }
            break;
        case CBManagerStateUnknown: // 未知
        {
            /* Bad news, let's wait for another event. */
            DebugNSLog(@"StateChange = CBManagerStateUnknown");

        }
            break;
        case CBManagerStatePoweredOn:// 开启
        {
            DebugNSLog(@"StateChange = CBManagerStatePoweredOn");

            isOn = YES;
        }
            break;
        case CBManagerStateResetting:// 重置中
        {
            DebugNSLog(@"StateChange = CBManagerStateResetting");

            break;
        }
    }
}
- (void)caBleDidConnectPeripheral:(nonnull CABLeService *)service {
    self.bleBtn.selected = YES;

    [LTPHud.Instance showText:@"Connect CABLeService successfully!"];
    [CARingSDK.instance setCurrentPeripheralService:service]; // MARK: important

}

- (void)caBleDidDisconnectPeripheral:(nonnull CABLeService *)service {
    self.bleBtn.selected = NO;
    self.hrSpoRealMeaBtn.selected = NO;
    self.deviceInfo = nil;
    [CARingSDK.instance setCurrentPeripheralService:nil];// MARK: important

}

- (void)caBleRealtimeHRV:(NSNumber *)hrv BloodOxygen:(NSNumber *)bloodOxygen HeartRate:(NSNumber *)hr Status:(REALTIME_STATUS)status {
    
    if (status != REALTIME_STATUS_DATA_USEFUL) {
        return;
    }

  
    
}






- (void)caBleDeviceDidReadyForReadAndWrite:(nonnull CABLeService *)service {
    
    DebugNSLog(@"device service is ready");
    



    
}

/// call back device's battery level and charging state
/// @param batteryLevel battery level
/// @param isCharging YES = device is charging
- (void)caBleDeviceBatteryLevel:(NSInteger)batteryLevel IsCharging:(BOOL)isCharging
{
    
    DebugNSLog(@"battery :%lu ischarging %d", (unsigned long)batteryLevel, isCharging);
    [self.textView addNewText:[NSString stringWithFormat:@"Power:%ld%% Charging:%@", batteryLevel, isCharging ?_L2(L_YES) : _L2(L_NO)]];
    
}


/// call back value of device's sn code
/// @param sn sn code
- (void)caBleSN:(NSString *)sn SnData:(NSData *)snData {
    // HEAD_SN
    DebugNSLog(@"call back sn : %@", sn);
    [self.textView addNewText:[NSString stringWithFormat:@"%@:%@", HEAD_SN, sn]];
}

- (void)caBleDeviceInfo:(CADeviceInfo *)devInfo {
    /*
     self.bindDevice.otherInfo.isSupportEcg = self.sdk.currentDevice.isSupportEcg;
     self.bindDevice.otherInfo.ecgCalcType = devInfo.ecgCalcType;

     self.bindDevice.otherInfo.projectId = devInfo.projectId;
     self.bindDevice.otherInfo.isSelfDevelopedAlgorithm = devInfo.isSelfDevelopedAlgorithm;
     */
    self.deviceInfo = devInfo;
    DebugNSLog(@"call back device info: %@", devInfo);
    // needOemAuth oem 认证
    [self.textView addNewText:devInfo.wholeInfomationDescText];
    
    [[CARingSDK instance] functionGetDeviceSN];
    
}

-(void)caBleOEMAuthResult:(BOOL)authSucceddful
{
    DebugNSLog(@"OEM auth result :%@", authSucceddful? @"yes": @"no");
    if (authSucceddful) {
        [LTPHud.Instance showText:@"OEM auth successful"];
        
    } else {
        NSString *msg = [NSString stringWithFormat:@"%@ Class:%@,Line:%d",
         @"Auth failed.Different manufacter!",
         NSStringFromClass([ self class]),
         __LINE__];
        [self showAlertWarningWithTitle:@"Tips" Msg:msg btnCancel:_L2(L_OK) Compelete:nil];
        return;
    }
}



- (void)caBleIsBinded:(BOOL)isBinded
{
    NSString *string = [NSString stringWithFormat:@"Ring is %@",
                        isBinded ?@"bound" :@"unbind" ];
    [self.textView addNewText:string];
    
}





/// call back realtime steps
/// @param steps moving steps
- (void)caBleDeviceRealtimeSteps:(NSNumber *)steps IsDeviceFix:(BOOL)isDeviceFixed  {
    self.stpes = steps;
//    [self reloadWithTag:TAG_STEP];
    DebugNSLog(@"计步 : %@", steps);
}


/// call back realtime skin temperature
/// @param temperature skin temperature
- (void)caBleDeviceRealtimeTemperature:(NSNumber *)temperature {
    self.temperature = temperature;
//    [self reloadWithTag:TAG_TEMP];
    DebugNSLog(@"体温 : %@", temperature);

}

- (void)caBleCmdExcute:(EXCUTED_CMD)cmd Succ:(BOOL)isSucc Reason:(CA_CMD_EXECTE_ERROR_REASON)reason Data:(nonnull NSData *)originData
{
    
    DebugNSLog(@"command : %d excute result: %d", cmd, isSucc);
    
    if ((cmd == EXCUTED_CMD_HIS_DATA || cmd ==EXCUTED_CMD_GET_HIS_DATA_ACT_SWIM_SLEEP) && !isSucc )
    {

        if (cmd == EXCUTED_CMD_HIS_DATA) {
            [CARingSDK.instance functionRsetTranslatingHistoryState];
        }
        // 提示原因
        NSString *msg1 = [NSString stringWithFormat:_L2(L_CMD_EXCUTE_FMT_REASON), [CADeviceInfo descryOfErrorReason:reason], reason ];
        
        // ring is measuring
        NSString *msg2 = @"";
        if (    CA_REASON_1 == reason) {
            msg2 = _L2(L_TRY_AGAIN);
        }
        // workouting- end workout first
        if (    CA_REASON_2 == reason) {
            msg2 = _L2(L_END_WK_FIRST);
        }
        [self showAlertWarningWithTitle:@"Error" Msg:[msg1 stringByAppendingString:msg2] btnCancel:_L2(L_OK) Compelete:nil];
    }
    
}

/// User information reporting
/// - Parameters:
///   - gender:  0 male, 1 female
///   - ageYear: range 1-115
///   - height:  in mm, range 1200-3000
///   - weight:  in kg, range 30-200
-(void)caBleUsrInfoFromoDev:(NSUInteger)gender
                Age:(NSUInteger)ageYear
              Height:(NSUInteger)height
                     Weight:(NSUInteger)weight
{

    NSString *usrInfoTxt = [CADeviceInfo stringFromUserInfo:gender Age:ageYear Height:height Weight:weight];
    [self.textView addNewText:usrInfoTxt];
    
}

- (void)caBleHistorySr03Data:(CAHistoryDataSR03 *)hisData IsComplete:(BOOL)isComplete;
{
    self.his_1_countIdx++;
    if (hisData) {
        NSString *log = [NSString stringWithFormat:@"%ld %@", self.his_1_countIdx, [hisData wholeDesc]];
        [self.textView addNewText:log];
//        [self.textView addNewText:[NSString stringWithFormat:@"recv history 1 idx: %ld, all:%ld", self.countIdx, self.allCount]];
    }
    if (isComplete) {
        [self.textView addNewText:@"Sync complete."];

    }
    
    
}

- (void)caBleHistoryDataCount:(NSInteger)count {
    [self.textView addNewText:[NSString stringWithFormat:@"history 1 count: %ld", (long)count]];
    self.his_1_countIdx = 0;
    self.his_1_allCount = count;
}

- (void)caBleHistoryDataTimeout {
    [self.textView addNewText:@"Sync history 1 time out!"];
}



-(void)caBleLastActivity:(CAnAlgGrandActivity*)activity
{
    
    [self.textView addNewText:[activity wholeDesc]];

}

/// Report the number of activity detection/swimming/sleep history data
/// - Parameters:
///   - count: The amount of data
///   - minUUid: The minimum uuid of the data reported this time
///   - maxUUid: The maximum uuid of the data reported this time
-(void)caBleHisCntOfActivityAndSwimAndSleep:(NSUInteger)count MinUUid:(uint32_t)minUUid MaxUUid:(uint32_t)maxUUid
{
    [self.textView addNewText:[NSString stringWithFormat:@"histoy2 count: %lu, UUID: %u - %u", count, minUUid, maxUUid]];

}

// Callback Report activity detection/exercise/new historical data/body temperature historical data/sleep data
-(void)caBleNalgDeviceMeasurHinstoryData:(id<CANalgProtocal>)dataObj
{
    
    if ([dataObj isKindOfClass:[CAHistoryDataNALG class]]) {
        [self.textView addNewText:((CAHistoryDataNALG*)dataObj).wholeDesc];

    }
    
    if ([dataObj isKindOfClass:[CAnAlgAutoDetecActivity class]])
    {
        DebugNSLog(@"receive CAnAlgAutoDetecActivity");
        [self.textView addNewText:((CAnAlgAutoDetecActivity*)dataObj).wholeDesc];

    }
    
    
    if ([dataObj isKindOfClass:[CAnAlgExerData class]])
    {
//        DebugNSLog(@"receive CAnAlgExerData");
        [self.textView addNewText:((CAnAlgExerData*)dataObj).wholeDesc];

    }
    
    if ([dataObj isKindOfClass:[CAnAlgSwimSumData class]])
    {
        DebugNSLog(@"receive CAnAlgSwimSumData 游泳汇总");
        [self.textView addNewText:((CAnAlgSwimSumData*)dataObj).wholeDesc];

    }
    
    if ([dataObj isKindOfClass:[CAnAlgSwimLapData class]])
    {
        DebugNSLog(@"receive CAnAlgSwimLapData 游泳单圈");
        [self.textView addNewText:((CAnAlgSwimLapData*)dataObj).wholeDesc];

    }
    
    if ([dataObj isKindOfClass:[CAnAlgSleep class]])
    {
        DebugNSLog(@"receive CAnAlgSleep");
        // 存储
        [self.textView addNewText:((CAnAlgSleep*)dataObj).wholeDesc];

    }
    
    if ([dataObj isKindOfClass:[CAnAlgGrandActivity class]])  // 0xca 0xc8
    {
        DebugNSLog(@"receive CAnAlgGrandActivity year: %d, month %d, day %d",((CAnAlgGrandActivity*)dataObj).year, ((CAnAlgGrandActivity*)dataObj).month, ((CAnAlgGrandActivity*)dataObj).day );
        [self.textView addNewText:((CAnAlgGrandActivity*)dataObj).wholeDesc];
    }
    
    if ([dataObj isKindOfClass:[CAnAlgExerVitalSignsData class]])  // 0xcc
    {
//        [self.vitalSignsDataCacheArray addObject:(CAnAlgExerVitalSignsData *)dataObj];
        [self.textView addNewText:((CAnAlgExerVitalSignsData*)dataObj).wholeDesc];

    }
    
    // Body temperature during sleep
    if ([dataObj isKindOfClass:[CAnAlgSkinTempAsleep class]])  // 0xCE
    {
//        [self.textView addNewText:((CAnAlgSkinTempAsleep*)dataObj).wholeDesc];

    }
    
}

-(void)caBleNALGRealMeasu:(CAnAlgRealMeasure *)realMeasurData
{
    [self.textView addNewText:[realMeasurData wholeDesc]];
}

#pragma mark -- Button Selector

-(void)bleBtnClick:(QMUIButton *)btn {
    if ([[CARingSDK instance] currentDevice].isConnected == YES) { // already connected
        
        [[CARingSDK instance] disconnectCurrentService]; //disconnect current device
    } else {
        // 两种扫描
        WEAK_SELF
        UIAlertController * alertVc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        
//        UIAlertAction *actionInnerScan = [UIAlertAction actionWithTitle:_L2(L_in_sdk_scan) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            STRONG_SELF
//            // push to connect vc
//            SRConnectVc *connectVC = [SRConnectVc new];
//            
//            [strongSelf.navigationController pushViewController:connectVC animated:YES];
//        }];
//
//        [alertVc addAction:actionInnerScan];
        
        UIAlertAction * actionCustomScan = [UIAlertAction actionWithTitle:_L2(L_custom_scan) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            STRONG_SELF
            CAOutsideConnectVc *outsdConVc = [CAOutsideConnectVc new];
            outsdConVc.ousideBleManager = strongSelf.ousideBleManager;
            [strongSelf.navigationController pushViewController:outsdConVc animated:YES];
        }];
       
        [alertVc addAction:actionCustomScan];
      
            
        UIAlertAction * actionCancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
        [alertVc addAction:actionCancel];

        [self presentViewController:alertVc animated:YES completion:nil];
        
      
    }
}

-(void)goToSetting:(UIButton *)btn {
    if ([[CARingSDK instance] currentDevice].isConnected != YES) {
        // device not connected
        [LTPHud.Instance showText:_L2(L_TXT_CON_FIRST)];
        return;
    }
    
    CASettingVc *vc = [CASettingVc new];
    [self.navigationController pushViewController:vc animated:YES];
    
}
#pragma mark -- Lazy

-(QMUIButton *)bleBtn
{
    if (!_bleBtn) {
        _bleBtn = [[QMUIButton alloc]init];
        [_bleBtn setImage:[UIImage imageNamed:@"ble_disconect"] forState:UIControlStateNormal];
        [_bleBtn setImage:[UIImage imageNamed:@"ble_connect"] forState:UIControlStateSelected];
        [_bleBtn addTarget:self action:@selector(bleBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _bleBtn;
}
-(QMUIButton *)settingBtn
{
    if (!_settingBtn) {
        _settingBtn = [[QMUIButton alloc]init];
        [_settingBtn setImage:[UIImage imageNamed:@"setting"] forState:UIControlStateNormal];
        [_settingBtn addTarget:self action:@selector(goToSetting:) forControlEvents:UIControlEventTouchUpInside];

    }
    return _settingBtn;
}
-(UIScrollView *)btnScrollView
{
    if(!_btnScrollView) {
        _btnScrollView = [UIScrollView new];
        _btnScrollView.showsVerticalScrollIndicator = YES;
        _btnScrollView.showsHorizontalScrollIndicator = NO;
    }
    return _btnScrollView;
}

-(DynamicTextView *)textView
{
    if (!_textView) {
        _textView = [[DynamicTextView alloc]initWithFrame:CGRectZero];
        _textView.layer.borderWidth = 1.0f;
        _textView.layer.borderColor = MAIN_BLUE.CGColor;
        [_textView setFont:[UIFont systemFontOfSize:15]];
    }
    return _textView;
}

-(UILabel *)topLable
{
    if (!_topLable) {
        _topLable = [UILabel new];
        _topLable.numberOfLines = 0;
        _topLable.font = [UIFont systemFontOfSize:17];
        _topLable.adjustsFontSizeToFitWidth = YES;
    }
    return _topLable;
}

@end
